use chrono::{DateTime, Local};
use wasm_bindgen::JsValue;
use web_sys::{ Element};
use web_sys::wasm_bindgen::JsCast;
use yew::{function_component, html, use_context, use_node_ref, Callback, Children, Html, Properties};
use crate::business::app_state::AppState;
use crate::business::websocket::dto::rpc_data::RpcData;
use crate::business::websocket::dto::user_dto::{LoginReq, TerminalType};

#[derive(Properties, PartialEq, Clone)]
pub struct ModelProp {
    pub id: String,
    pub class: Option<String>,
    pub title: String,
    pub can_close: bool,
    pub children: Children,
}

#[function_component(Model)]
pub fn model(prop: &ModelProp) -> Html {
    let ModelProp {id, class, title, can_close, children: other_children} = prop.clone();

    let modal_ref = use_node_ref();
    
    let app_state = use_context::<AppState>().unwrap();

    log::info!("html!!!!!!!!!!!!!!!!!!!!!!!!!!!!, app_state: {:?}", app_state);

    // let list = db::sqlite::query();
    //
    // log::info!("html!!!!!!!!!!!!!!!!!!!!!!!!!!!!222, {}", list.iter().map(|e: &Employee| format!("{}-{}-{}", &e.id, &e.name, &e.salary)).collect::<Vec<String>>().join(","));

    let login_req = LoginReq {
        user_id: "test001".to_string(),
        password: "123456".to_string(),
        machine_code: "123".to_string(),
        tenant_code: "".to_string(),
        terminal_type: TerminalType::Pc,
        create_date_time: DateTime::from(Local::now()),
        local_seq: "112".to_string(),
    };

    let rpc_data = RpcData::new("login".to_owned(), login_req, "11111".to_owned());
    let json : String = rpc_data.into();
    log::info!("json: {}", json);
    let _new_rpc_data: RpcData<LoginReq> = RpcData::from(json.clone());

    let aria_labeled = format!("{}Label", &id);
    let _model_title_id = format!("{}ModelLabel", &id);

    let model_id = format!("{}", id.clone());
    log::info!("model_id: {}", &model_id);
    let model_ref_2 = modal_ref.clone();
    let callback = Callback::from(move |_| {
        if let Some(_modal_element) = model_ref_2.cast::<Element>() {
            log::info!("modal begin close!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!: {}", &model_id);
            // let event = Event::new("hidden.bs.modal").unwrap();
            // modal_element.dispatch_event(&event).unwrap();

            if let Some(window) = web_sys::window() {
                if let Some(document) = window.document() {
                    // 查找所有关闭按钮并触发点击
                    if let Ok(buttons) = document.query_selector_all("[data-bs-dismiss='modal']") {
                        for i in 0..buttons.length() {
                            if let Some(button) = buttons.item(i) {
                                button.dyn_ref::<web_sys::HtmlElement>()
                                    .unwrap()
                                    .click();
                            }
                        }
                    }
                }
            }

            // let modal_instance = js::bootstrap::Modal::new(&modal_element);
            // modal_instance.hide();

            // let modal = Bootstrap::Modal(&modal_element);
            // modal.hide();
            // let js_command = format!("var model = bootstrap.Modal.getInstance(document.getElementById('{}'));
            //     model.toggle(); ", modal_element.id());
            // // // let js_command2 = format!("document.getElementById('{}').dispatchEvent(new Event('hidden.bs.modal'));", modal_element.id());
            // // // log::info!("js_command: {}", js_command2);
            // let _ = js_sys::eval(&js_command);
        }
    });

    html! {
        <div class="modal fade" ref= { modal_ref } id={ id } tabindex="-1" aria-labelledby={ aria_labeled.clone() } aria-hidden="true">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id={ aria_labeled.clone() }>{ title }</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
              </div>
              <div class="modal-body">
                { for other_children.iter() }
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">{"Close"}</button>
                <button type="button" class="btn btn-primary" onclick= { callback }>{"Save changes"}</button>
              </div>
            </div>
          </div>
        </div>
    }
}

pub fn close_modal(model_id: &str) {
    let window = web_sys::window().expect("should have a window in this context");
    let document = window.document().expect("window should have a document");
    let modal_element: Element = document.get_element_by_id(model_id).expect("modal should be in the document");

    let bootstrap_modal = web_sys::Element::from(modal_element).unchecked_into::<web_sys::HtmlElement>();
    let bs_modal = web_sys::HtmlElement::from(bootstrap_modal);
    let modal = bs_modal.dyn_into::<js_sys::Object>().unwrap();
    let _ = js_sys::Reflect::set(
        &modal,
        &JsValue::from_str("bsModal"),
        &JsValue::NULL,
    ); // 这行代码实际上并不关闭Modal，只是为了示例如何调用JS对象的方法。正确的方法是使用Bootstrap的API。

    // 使用Bootstrap的方法关闭Modal
    let _ = js_sys::Reflect::set(
        &modal,
        &JsValue::from_str("hide"),
        &JsValue::undefined(),
    ).unwrap();
}